package com.etooling.framework.controller;

import com.etooling.framework.entity.Employee;
import com.etooling.framework.entity.FuncModule;
import com.etooling.framework.entity.Role;
import com.etooling.framework.repository.AttachFileRepository;
import com.etooling.framework.repository.EmployeeRepository;
import com.etooling.framework.repository.OrgRepository;
import com.etooling.framework.repository.RoleRepository;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.VoToPoUtil;
import com.etooling.framework.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/admin/role")
/**
 * @title: DataDirController
 * @description: TODO
 * @author 周志荣
 * @date 2020/12/19 12:11
 */
public class RoleController {
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    OrgRepository orgRepository;
    @Autowired
    AttachFileRepository attachFileRepository;

    @RequestMapping("pageQuery")
    @ResponseBody
    /**
     　　 @description:
    　　 @param [request, dataDirConf, pageSize, page, isUnion, searchName] 
    　　 @return com.irobot.framework.svo.ReplyObj
    　　 @throws
    　　 @author 周志荣
    　　 @date 2020/12/20 18:25 
    　　*/
    ReplyObj pageQuery(HttpServletRequest request,

                       @RequestParam(defaultValue = "30", required = false, value = "pageSize") int pageSize,
                       @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                       @RequestParam(defaultValue = "yes", required = false, value = "isUnion") String isUnion,
                       @RequestParam(defaultValue = "", required = false, value = "name") String name
    ) {
        Sort sort = Sort.by(Sort.Direction.ASC, "name");//使用一个序
        //分页
        Pageable pageable = PageRequest.of(page - 1, pageSize, sort);
        Specification<Role> spec = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                String orgId = (String) WebUtils.getSessionValue(request, WebUtils.LOGIN_ORG_ID_KEY);
//                Join<Role, Org> joinOrg = root.join("org", JoinType.LEFT);
//                predicates.add(cb.equal(joinOrg.get("id"), orgId));

                // predicates.add(cb.equal(root.join("org"), orgId));
                //将条件根据变量放进条件列表中
                if (WebUtils.checkStr(name)) {
                    predicates.add(cb.like(root.get("name"), "%" + name + "%"));
                }
                //返回条件
                return WebUtils.getPredicates(predicates, isUnion, cb);
            }
        };
        Page<Role> pageList = roleRepository.findAll(spec, pageable);
        return WebUtils.flushSuccess(pageList);

    }


    @RequestMapping("/getAllRoles")
    @ResponseBody
    ReplyObj getAllRoles(HttpServletRequest request
    ) {

        List<Role> roleList = roleRepository.findAll();
        System.out.println(roleList.size());
        return WebUtils.flushObjSuccess(roleList);

    }

    @RequestMapping("add")
    @ResponseBody
    ReplyObj add(HttpServletRequest request, Role role
    ) {
        roleRepository.save(role);
        return WebUtils.flushSuccess();
    }


    @RequestMapping("update")
    @ResponseBody
        /*
         * @description: 修改机构
         * @param [request, org, newOrgId]
         * @return com.irobot.framework.svo.ReplyObj
         * @throws
         * @author 周志荣
         * @date 2020/12/18 18:13
         */
    ReplyObj update(HttpServletRequest request, Role vo) {
        try {
            //测试
            Role po = roleRepository.findById(vo.getId()).get();
            VoToPoUtil.copyProperties(po, vo);
            roleRepository.save(po);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure("数据错误，请联系统管理员");
        }

    }

    @RequestMapping("del")
    @ResponseBody
    ReplyObj del(HttpServletRequest
                         request, @RequestParam(defaultValue = "", required = false, value = "id") String id) {
        try {
            Role role = roleRepository.findById(id).get();
            roleRepository.delete(role);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }

    @RequestMapping("acceptRoleModules")
    @ResponseBody
    ReplyObj acceptRoleModules(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "roleId") String roleId,
                               @RequestParam(defaultValue = "", required = false, value = "checkModules") String checkModuleIds
    ) {
        String checkModules[] = {};
        if (WebUtils.checkStr(checkModuleIds)) {
            checkModules = checkModuleIds.split(",");
        }
        List<FuncModule> moduls = new ArrayList();
        for (String moduleId : checkModules) {
            FuncModule m = new FuncModule();
            m.setId(moduleId);
            moduls.add(m);
        }
        Role role = roleRepository.findById(roleId).get();
        role.setFuncModules(moduls);

        roleRepository.saveAndFlush(role);
        return WebUtils.flushSuccess();
    }

    @Autowired
    EmployeeRepository employeeRepository;

    @RequestMapping("getEmployeeListByRoleName")
    @ResponseBody
    ReplyObj getEmployeeListByRoleName(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "roleName") String roleName
    ) {
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        List<Employee> employees = employeeRepository.getListByRoleName(roleName, companyId);
        return WebUtils.flushSuccess(employees);
    }

}
